<template>
  <view>
    <!-- 地址 -->
    <view class="addressWrapper">
      <view v-if="!address" class="btn" @click="chooseAddress">选择地址</view>
      <view v-else class="addressInfo">
        <view class="address">{{address}}</view>
        <view class="user">{{user}}</view>
      </view>
    </view>
    <!-- 商品列表 -->
    <view class="goodsList">
      <view class="goodsItem u-flex" v-for="item in checkedGoodsList" :key="item.goods_id">
        <!-- 左 -->
        <u-image :src="item.pic" width="190" height="190"></u-image>
        <!-- 右 -->
        <view class="info u-flex">
          <view class="top u-line-2">{{item.goods_name}}</view>
          <view class="bottom u-flex">
            <view class="price">￥ {{item.goods_price}}</view>
            <view class="number u-flex">
              <view class="shuzi"> x{{item.number}}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 底部状态 -->
    <view class="cartBottom u-flex">
      <view class="totalPrice u-flex-1">
        合计 <text class="price">￥ {{totalPrice}}</text>
      </view>
      <view @click="handlePayment" class="submitBtn">
        去支付({{totalGoodsNumber}})
      </view>
    </view>
  </view>
</template>

<script>
import {mapGetters, mapMutations, mapState, mapActions} from 'vuex'
export default {
  data() {
    return {
      address: '',
      user: ''
    }
  },
  computed: {
    ...mapState('user', ['token']),
    ...mapGetters('cart', ['totalGoodsNumber', 'totalPrice', 'checkedGoodsList'])
  },
  methods: {
    ...mapActions('user', ['wxLogin']),
    ...mapMutations('cart', ['clearCartAfterPayment']),
    async chooseAddress() {
      const [err, res] = await uni.chooseAddress()
      console.log(res);
      if (!err) {
        this.address = `${res.provinceName}${res.cityName}${res.countyName} ${res.detailInfo} ${res.nationalCode}`
        this.user = `${res.userName} ${res.telNumber}`
      }
    },
    async handlePayment() {
      // TODO 如果没地址, 不能发请求
      if (!this.address) {
        uni.showToast({title: '先选择收货地址', icon: 'none'})
        return
      }

      // 获取 token
      // 因为已经封装到 vuex 当中了, 所以检查有没有数据, 没有再登录
      // const token = await this.wxLogin()
      if (!this.token) {
        await this.wxLogin()
      }
      // 创建订单
      const order_number = await this.createOrder()
      // 创建付款单
      const pay = await this.createPayment(order_number)
      // 调起支付
      const [errPay, resPay] = await uni.requestPayment(pay)
      if (!errPay) {
        console.log('付款成功');
        console.log(resPay);
        // 调用一个清理已购买商品的 mutations
        // 跳转回购物车页面
        this.clearCartAfterPayment()
        // 因为购物车时底部存在的 tab 页面必须用 switchTab 操作
        uni.switchTab({url: '/pages/cart/cart'})
      }
    },
    // 封装登录, 会返回 token
    // async wxLogin() {
    //   // 获取用户信息
    //   const [errProfile, resProfile] = await uni.getUserProfile({desc: '为了给用户提供更好的服务'})
    //   // 获取通行凭证
    //   const [errLogin, resLogin] = await uni.login()

    //   if (!errProfile && !errLogin) {
    //     const {encryptedData,rawData,iv,signature} = resProfile
    //     const {code} = resLogin
    //     // 发请求微信形式登录
    //     const res = await this.$u.post('/users/wxlogin', {
    //       encryptedData,rawData,iv,signature,code
    //     })
    //     const {token} = res.message
    //     console.log(token);
    //     return token
    //   }else {
    //     uni.showToast({title: '登录失败 支付取消', icon: 'none'})
    //   }
    // },
    // 封装创建订单, 接收token为形参, 会返回订单编号
    async createOrder () {
      // 创建订单获取订单编号
      const data = {
        order_price: this.totalPrice,
        consignee_addr: `${this.address} ${this.user}`,
        goods: this.checkedGoodsList.map(item=>{
          return {
            goods_id: item.goods_id,
            goods_number: item.number,
            goods_price: item.goods_price
          }
        })
      }
      // console.log(data);
      const res = await this.$u.post('/my/orders/create', data)

      return res.message.order_number
    },
    // 封装创建预付单, 接收token + 订单编号, 返回付款参数
    async createPayment(order_number) {
      const data = {
        order_number
      }
      const res = await this.$u.post('/my/orders/req_unifiedorder', data)
      return res.message.pay
    }
  }
}
</script>

<style lang="scss" scoped>
.addressWrapper {
  padding: 70rpx 20rpx;
  height: 188rpx;
  border-bottom: 20rpx solid #f9f9f9;
  display: flex;
  justify-content: center;
  align-items: center;
  .addressInfo {
    width: 100%;
    padding: 0 30rpx;
    font-size: 30rpx;
    color: #434343;
    .user {
      font-size: 26rpx;
      margin-top: 20rpx;
    }
  }
  .btn {
    width: 302rpx;
    line-height: 90rpx;
    border-radius: 45rpx;
    text-align: center;
    color: $theme-color;
    border: 3rpx solid $theme-color;
  }
}
.goodsList { 
  padding: 20rpx;
}
.goodsItem {
  margin: 0 0 20rpx;
}
.info {
  flex: 1;
  margin-left: 20rpx;
  flex-direction: column;
  height: 190rpx;
  padding: 26rpx 0;
  justify-content: space-between;
  .top {
    width: 100%;
    font-size: 24rpx;
  }
  .bottom {
    width: 100%;
    justify-content: space-between;
    .price {
      color: $theme-color;
      font-size: 24rpx;
    }
    .number {
      font-size: 32rpx;
      .shuzi {
        margin: 0 10rpx;
      }
    }
  }
}

.cartBottom {
  height: 84rpx;
  padding: 0 34rpx;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  background: #fdfdfd;
  border-top: 1px solid #f5f5f5;
  .totalPrice {
    font-size: 28rpx;
    font-weight: bold;
    margin-left: 10rpx;
    .price {
      font-size: 32rpx;
      color: $theme-color;
      font-weight: normal;
    }
  }
  .submitBtn {
    background: $theme-color;
    color: #ffffff;
    line-height: 52rpx;
    padding: 0 26rpx;
    border-radius: 26rpx;
    font-size: 22rpx;
  }
}
</style>